import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import './filePanel.css';
import '@/font/SmileySans-Oblique.ttf';

interface FileItem {
  name: string;
  path: string;
  size?: number;
  modifiedTime: string;
  isDirectory: boolean;
  selected?: boolean;
}

const FilePanel: React.FC = () => {
  const [currentPath, setCurrentPath] = useState<string>('/');
  const [files, setFiles] = useState<FileItem[]>([
    { name: 'Documents', path: '/documents', isDirectory: true, modifiedTime: '2024-01-01', selected: false },
    { name: 'Pictures', path: '/pictures', isDirectory: true, modifiedTime: '2024-02-01', selected: false },
        { name: 'Videos', path: '/videos', isDirectory: true, modifiedTime: '2024-03-01', selected: false },
    { name: 'Music', path: '/music', isDirectory: true, modifiedTime: '2024-04-01', selected: false },
    { name: 'file1.txt', path: '/documents/file1.txt', size: 1024, isDirectory:false, modifiedTime: '2024-01-10', selected: false },
]);
  const [searchQuery, setSearchQuery] = useState('');
  const [clipboard, setClipboard] = useState<{items: FileItem[], operation: 'copy'|'cut'}>();
  const [selectionBox, setSelectionBox] = useState<{start: {x: number, y: number}, end: {x: number, y: number}}>();
  const fileListRef = useRef<HTMLDivElement>(null);

  // 加载目录内容
  const loadDirectory = async (path: string) => {
    try {
      const response = await axios.get('/api/files', {
        params: { path: path }
      });
      setFiles(response.data.map((item: any) => ({
        ...item,
        selected: false
      })));
    } catch (error) {
      console.error('加载目录失败:', error);
    }
  };

  useEffect(() => {
    loadDirectory(currentPath);
  }, [currentPath]);

  // 处理文件选择
  const handleSelect = (file: FileItem, event: React.MouseEvent) => {
    const newFiles = [...files];
    if (event.ctrlKey || event.metaKey) {
      // 多选
      const index = newFiles.findIndex(f => f.path === file.path);
      newFiles[index].selected = !newFiles[index].selected;
    } else {
      // 单选
      newFiles.forEach(f => f.selected = f.path === file.path);
    }
    setFiles(newFiles);
  };

  // 处理框选
  const handleMouseDown = (e: React.MouseEvent) => {
    if (e.button !== 0) return;
    const rect = fileListRef.current?.getBoundingClientRect();
    if (!rect) return;
    
    const start = { x: e.clientX - rect.left, y: e.clientY - rect.top };
    setSelectionBox({ start, end: start });

    const onMouseMove = (e: MouseEvent) => {
      const end = { x: e.clientX - rect.left, y: e.clientY - rect.top };
      setSelectionBox(prev => ({ ...prev!, end }));
    };

    const onMouseUp = () => {
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
      
      if (selectionBox) {
        const selectedFiles = files.map(file => {
          const element = document.querySelector(`[data-path="${file.path}"]`);
          if (element) {
            const rect = element.getBoundingClientRect();
            const boxRect = {
              left: Math.min(selectionBox.start.x, selectionBox.end.x),
              right: Math.max(selectionBox.start.x, selectionBox.end.x),
              top: Math.min(selectionBox.start.y, selectionBox.end.y),
              bottom: Math.max(selectionBox.start.y, selectionBox.end.y)
            };
            return {
              ...file,
              selected: (
                rect.right > boxRect.left &&
                rect.left < boxRect.right &&
                rect.bottom > boxRect.top &&
                rect.top < boxRect.bottom
              )
            };
          }
          return file;
        });
        setFiles(selectedFiles);
      }
      setSelectionBox(undefined);
    };

    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('mouseup', onMouseUp);
  };

  // 文件操作
  const createFile = async (isDirectory: boolean) => {
    const name = prompt('请输入名称:');
    if (!name) return;
    
    try {
      await axios.post('/api/files', {
        path: currentPath,
        name,
        isDirectory
      });
      loadDirectory(currentPath);
    } catch (error) {
      console.error('创建失败:', error);
    }
  };

  const deleteFiles = async () => {
    const selected = files.filter(f => f.selected);
    if (!selected.length || !confirm('确定要删除选中的项目吗?')) return;
    
    try {
      await axios.delete('/api/files', {
        data: { paths: selected.map(f => f.path) }
      });
      loadDirectory(currentPath);
    } catch (error) {
      console.error('删除失败:', error);
    }
  };

  const renameFile = async (file: FileItem) => {
    const newName = prompt('请输入新名称:', file.name);
    if (!newName || newName === file.name) return;
    
    try {
      await axios.put('/api/files/rename', {
        path: file.path,
        newName
      });
      loadDirectory(currentPath);
    } catch (error) {
      console.error('重命名失败:', error);
    }
  };

  const copyFiles = () => {
    const selected = files.filter(f => f.selected);
    if (selected.length) {
      setClipboard({ items: selected, operation: 'copy' });
    }
  };

  const cutFiles = () => {
    const selected = files.filter(f => f.selected);
    if (selected.length) {
      setClipboard({ items: selected, operation: 'cut' });
    }
  };

  const pasteFiles = async () => {
    if (!clipboard) return;
    
    try {
      await axios.post('/api/files/paste', {
        items: clipboard.items.map(f => f.path),
        destination: currentPath,
        operation: clipboard.operation
      });
      loadDirectory(currentPath);
    } catch (error) {
      console.error('粘贴失败:', error);
    }
  };

  // 预览文件
  const previewFile = (file: FileItem) => {
    if (file.isDirectory) {
      setCurrentPath(file.path);
    } else {
      window.open(`/api/files/preview?path=${encodeURIComponent(file.path)}`, '_blank');
    }
  };

  // 过滤搜索结果
  const filteredFiles = files.filter(file => 
    file.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div className="file-panel">
      <div className="toolbar">
        <button onClick={() => setCurrentPath('/')}>↑</button>
        <input 
          type="text" 
          value={'/'} 
          readOnly 
          className="path-display"
          placeholder='/'
        />
        <input
          type="text"
          placeholder="搜索..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          className="search-box"
        />
        <button onClick={() => createFile(false)}>新建文件</button>
        <button onClick={() => createFile(true)}>新建文件夹</button>
        <button onClick={deleteFiles}>删除</button>
        <button onClick={copyFiles}>复制</button>
        <button onClick={cutFiles}>剪切</button>
        <button onClick={pasteFiles} disabled={!clipboard}>粘贴</button>
      </div>

      <div 
        className="file-list" 
        ref={fileListRef}
        onMouseDown={handleMouseDown}
      >
        {filteredFiles.map((file) => (
          <div 
            key={file.path}
            data-path={file.path}
            className={`file-item ${file.selected ? 'selected' : ''}`}
            onClick={(e) => handleSelect(file, e)}
            onDoubleClick={() => previewFile(file)}
            onContextMenu={(e) => {
              e.preventDefault();
              handleSelect(file, e);
            }}
          >
            <div className="file-icon">
              {file.isDirectory ? '📁' : '📄'}
            </div>
            <div className="file-name">{file.name}</div>
            <div className="file-size">{file.isDirectory ? '--' : formatSize(file.size)}</div>
            <div className="file-date">{formatDate(file.modifiedTime)}</div>
          </div>
        ))}
        {selectionBox && (
          <div 
            className="selection-box"
            style={{
              left: Math.min(selectionBox.start.x, selectionBox.end.x),
              top: Math.min(selectionBox.start.y, selectionBox.end.y),
              width: Math.abs(selectionBox.end.x - selectionBox.start.x),
              height: Math.abs(selectionBox.end.y - selectionBox.start.y)
            }}
          />
        )}
      </div>
    </div>
  );
};

// 辅助函数
function formatSize(bytes?: number): string {
  if (!bytes) return '--';
  const units = ['B', 'KB', 'MB', 'GB'];
  let size = bytes;
  let unitIndex = 0;
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }
  return `${size.toFixed(1)} ${units[unitIndex]}`;
}

function formatDate(dateString: string): string {
  const date = new Date(dateString);
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
}

export default FilePanel;